package org.yunai.swjg.server.core.message.codec;

import com.alibaba.fastjson.JSON;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.yunai.swjg.server.rpc.MessageManager;
import org.yunai.yfserver.message.AbstractEncoder;
import org.yunai.yfserver.message.ByteArray;
import org.yunai.yfserver.message.IMessage;

/**
 * 游戏消息编码器
 * User: yunai
 * Date: 13-1-31
 * Time: 上午1:14
 */
public class GameMessageEncoder implements ProtocolEncoder {

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
//        MessageWrapper messageWrap = (MessageWrapper) message;
//
//        AbstractEncoder encoder = MessageManager.getEncoder(messageWrap.getVocation());
//
//        ByteArray byteArray = encoder.encode(messageWrap.getBody());
//        int length = byteArray.limit() + 12;
//
//        IoBuffer buf = IoBuffer.allocate(length);
//        buf.putShort((short) length);
//        buf.putLong(0L);
//        buf.putShort(messageWrap.getVocation());
//        buf.put(byteArray.getHb());
//        buf.flip();
//        out.write(buf);
        IMessage msg = (IMessage) message;
        AbstractEncoder encoder = MessageManager.getEncoder(msg.getCode());

        ByteArray byteArray = encoder.encode(msg);
        int length = byteArray.limit() + 12;

        IoBuffer buf = IoBuffer.allocate(length);
        buf.putShort((short) length);
        buf.putLong(0L);
        buf.putShort(msg.getCode());
        buf.put(byteArray.getHb());
        buf.flip();
        out.write(buf);
System.err.println("[编码消息]: " + JSON.toJSONString(msg)); // TODO 调试作用
    }

    @Override
    public void dispose(IoSession session) throws Exception {
    }
}
